﻿using JNPF.Basics.Models;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 用户管理
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.09.20
    /// </summary>
    public class UserBll
    {
        private UserIService service = new UserService();
        private static List<UserEntity> userList = new List<UserEntity>();

        public UserBll()
        {
            if (CacheFactory.Cache.Exists(CacheKey.USERLIST))
            {
                userList = CacheFactory.Cache.Get(CacheKey.USERLIST).ToList<UserEntity>();
            }
            else
            {
                if (UserProvider.Instance.Get() != null)
                {
                    userList = service.GetList().Result;
                    CacheFactory.Cache.Insert(CacheKey.USERLIST, userList);
                }
            }
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<UserEntity>> GetList(PageInput input)
        {
            try
            {
                return await service.GetList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 查询管家角色下面的用户
        /// </summary>
        /// <param name="type">1:信贷 2：礼品 3：资源回收</param>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetListByRoles()
        {

            try
            {
                return await service.GetListByRoles();
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }


        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetList()
        {
            try
            {
                return await service.GetList();
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="positionId">岗位Id</param>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetListByPositionId(string positionId)
        {
            try
            {
                return await service.GetListByPositionId(positionId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="managerId">主管Id</param>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetListByManagerId(string managerId)
        {
            try
            {
                return await service.GetListByManagerId(managerId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<UserEntity> GetInfo(string id)
        {
            try
            {
                return await service.GetInfo(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<UserEntity> GetInfoByAccount(string account)
        {
            try
            {
                return await service.GetInfoByAccount(account);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 重复验证（账户）
        /// </summary>
        /// <param name="account">编码</param>
        /// <returns></returns>
        public async Task<bool> IsExistByAccount(string account, string id)
        {
            try
            {
                var condition = ExtLinq.True<UserEntity>().And(m => m.Account == account);
                if (!string.IsNullOrEmpty(id))
                    condition = condition.And(m => m.Id != id);
                return await service.IsExist(condition);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task Delete(UserEntity entity)
        {
            try
            {
                await service.Delete(entity);
                CacheFactory.Cache.Remove(CacheKey.USERLIST);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task Create(UserEntity entity)
        {
            try
            {
                #region 用户表单
                entity.Id = CommonHelper.Guid;
                entity.QuickQuery = PinyinHelper.PinyinString(entity.RealName);
                entity.Secretkey = CommonHelper.Guid.ToString();
                entity.Password = string.IsNullOrEmpty(entity.Password) ? Md5Helper.md5("e10adc3949ba59abbe56e057f20f883e" + entity.Secretkey).ToLower() : Md5Helper.md5(entity.Password.ToLower() + entity.Secretkey).ToLower();
                entity.CreatorTime = DateTime.Now;
                entity.LastModifyTime = DateTime.Now;
                entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                #endregion

                #region 用户关系
                List<UserRelationEntity> userRelationList = new List<UserRelationEntity>();
                //关联岗位
                if (entity.PositionId != null)
                {
                    var position = new List<string>(entity.PositionId.Split(','));
                    foreach (var item in position)
                    {
                        UserRelationEntity relationEntity = new UserRelationEntity();
                        relationEntity.Id = CommonHelper.Guid;
                        relationEntity.ObjectType = "Position";
                        relationEntity.ObjectId = item;
                        relationEntity.SortCode = position.IndexOf(item);
                        relationEntity.UserId = entity.Id;
                        relationEntity.CreatorTime = entity.CreatorTime;
                        relationEntity.CreatorUserId = entity.CreatorUserId;
                        userRelationList.Add(relationEntity);
                    }
                }
                //关联角色
                if (entity.RoleId != null)
                {
                    var roleId = new List<string>(entity.RoleId.Split(','));
                    foreach (var item in roleId)
                    {
                        UserRelationEntity relationEntity = new UserRelationEntity();
                        relationEntity.Id = CommonHelper.Guid;
                        relationEntity.ObjectType = "Role";
                        relationEntity.ObjectId = item;
                        relationEntity.SortCode = roleId.IndexOf(item);
                        relationEntity.UserId = entity.Id;
                        relationEntity.CreatorTime = entity.CreatorTime;
                        relationEntity.CreatorUserId = entity.CreatorUserId;
                        userRelationList.Add(relationEntity);
                    }
                }
                #endregion

                await service.Create(entity, userRelationList);
                CacheFactory.Cache.Remove(CacheKey.USERLIST);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task Update(string id, UserEntity entity)
        {
            try
            {
                #region 用户表单
                entity.Id = id;
                entity.QuickQuery = PinyinHelper.PinyinString(entity.RealName);
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyUserId = UserProvider.Instance.Get().UserId;
                #endregion

                #region 用户关系
                List<UserRelationEntity> userRelationList = new List<UserRelationEntity>();
                //关联岗位
                if (entity.PositionId != null)
                {
                    var position = new List<string>(entity.PositionId.Split(','));
                    foreach (var item in position)
                    {
                        UserRelationEntity relationEntity = new UserRelationEntity();
                        relationEntity.Id = CommonHelper.Guid;
                        relationEntity.ObjectType = "Position";
                        relationEntity.ObjectId = item;
                        relationEntity.SortCode = position.IndexOf(item);
                        relationEntity.UserId = entity.Id;
                        relationEntity.CreatorTime = DateTime.Now;
                        relationEntity.CreatorUserId = UserProvider.Instance.Get().UserId;
                        userRelationList.Add(relationEntity);
                    }
                }
                //关联角色
                if (entity.RoleId != null)
                {
                    var roleId = new List<string>(entity.RoleId.Split(','));
                    foreach (var item in roleId)
                    {
                        UserRelationEntity relationEntity = new UserRelationEntity();
                        relationEntity.Id = CommonHelper.Guid;
                        relationEntity.ObjectType = "Role";
                        relationEntity.ObjectId = item;
                        relationEntity.SortCode = roleId.IndexOf(item);
                        relationEntity.UserId = entity.Id;
                        relationEntity.CreatorTime = DateTime.Now;
                        relationEntity.CreatorUserId = UserProvider.Instance.Get().UserId;
                        userRelationList.Add(relationEntity);
                    }
                }
                #endregion

                await service.Update(entity, userRelationList);
                CacheFactory.Cache.Remove(CacheKey.USERLIST);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> UpdateState(string id, UserEntity entity)
        {
            try
            {
                CacheFactory.Cache.Remove(CacheKey.USERLIST);
                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> UpdatePassword(string id, UserEntity entity)
        {
            try
            {
                CacheFactory.Cache.Remove(CacheKey.USERLIST);
                entity.Secretkey = CommonHelper.Guid.ToString();
                entity.Password = Md5Helper.md5(entity.Password.ToLower() + entity.Secretkey).ToLower();
                entity.ChangePasswordDate = DateTime.Now;
                entity.Id = id;
                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="account">账户</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public async Task<UserEntity> CheckLogin(string account, string password)
        {
            try
            {
                var currentTime = DateTime.Now;
                var currentIp = Net.Ip;

                UserEntity userEntity = await service.GetInfoByAccount(account);
                if (userEntity == null)
                    throw new Exception("无效的账号");
                if (userEntity.EnabledMark == null)
                    throw new Exception("账号未被激活");
                if (userEntity.EnabledMark == 0)
                    throw new Exception("账号已被禁用");
                if (userEntity.DeleteMark == 1)
                    throw new Exception("账号已被删除");
                var str = Md5Helper.md5(password.ToLower() + userEntity.Secretkey).ToLower();
                if (Md5Helper.md5(password.ToLower() + userEntity.Secretkey).ToLower() != userEntity.Password.ToLower())
                    throw new Exception("账户或密码错误，请重新输入");
                userEntity.FirstLogTime = userEntity.FirstLogTime == null ? currentTime : userEntity.FirstLogTime;
                userEntity.FirstLogIP = userEntity.FirstLogIP == null ? currentIp : userEntity.FirstLogIP;
                userEntity.PrevLogTime = userEntity.LastLogTime != null ? userEntity.LastLogTime : null;
                userEntity.PrevLogIP = userEntity.LastLogIP != null ? userEntity.LastLogIP : null;
                userEntity.LastLogTime = currentTime;
                userEntity.LastLogIP = currentIp;
                userEntity.LogSuccessCount = userEntity.LogSuccessCount == null ? 1 : userEntity.LogSuccessCount + 1;
                await service.Update(userEntity);
                return userEntity;
            }
            catch (Exception ex)
            {
                throw new ExceptionEx(ex.Message, ex);
            }
        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="account">账户</param>
        /// <returns></returns>
        public async Task<UserEntity> CheckLogin(string account)
        {
            try
            {
                var currentTime = DateTime.Now;
                var currentIp = Net.Ip;
                UserEntity userEntity = await service.GetInfoByAccount(account);
                userEntity.FirstLogTime = userEntity.FirstLogTime == null ? currentTime : userEntity.FirstLogTime;
                userEntity.FirstLogIP = userEntity.FirstLogIP == null ? currentIp : userEntity.FirstLogIP;
                userEntity.PrevLogTime = userEntity.LastLogTime != null ? userEntity.LastLogTime : null;
                userEntity.PrevLogIP = userEntity.LastLogIP != null ? userEntity.LastLogIP : null;
                userEntity.LastLogTime = currentTime;
                userEntity.LastLogIP = currentIp;
                userEntity.LogSuccessCount = userEntity.LogSuccessCount == null ? 1 : userEntity.LogSuccessCount + 1;
                await service.Update(userEntity);
                return userEntity;
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 根据id获取用户名
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetUserName(string id)
        {
            if (id.IsNullOrEmpty())
            {
                return "";
            }
            var userInfo = userList.Find(u => u.Id == id);
            if (userInfo != null)
            {
                return userInfo.RealName + "/" + userInfo.Account;
            }
            else
            {
                return "";
            }
        }
    }
}
